import { FormItem, InputNumber, RadioGroup, Switch, Input, Select, ColorPicker, Button, Space } from '@arco-design/web-vue'
import Draggable from 'vuedraggable'
import Upload from '@/components/upload/index.vue'
import { message, get } from '@/utils'
import { h } from 'vue'
/**
 * 渲染配置相关
 */
const componentOptions = (props: DiyConfigOptions, formModal) => {
  if (props.customComponentOptions instanceof Function) {
    return props.customComponentOptions(formModal)
  } else return props.customComponentOptions
}
export default () => {
  const renderMethod = (item, formModal) => {
    const { type } = item
    let method: any
    switch (type) {
      case 'radio':
        method = renderRadio
        break
      case 'textarea':
        method = renderTextarea
        break

      case 'radio-button':
        method = renderRadioBtn
        break
      case 'input':
        method = renderInput
        break
      case 'input-number':
        method = renderInputNumber
        break
      case 'select':
        method = renderSelect
        break
      case 'color':
      case 'color-group':
        method = renderColor
        break
      case 'switch':
        method = renderSwitch
        break
      case 'upload':
        method = renderUpload
        break
      case 'checkbox':
        method = renderCheckboxGroup
        break
      case 'drag-list':
        method = renderDragList
        break

      case 'custom':
        const props = {
          val: formModal[item.valueKey],
          ...item.customComponentOptions,
        }
        method = () =>
          h(item.component, {
            ...props,
            onChange: e => {
              console.log(e)
              formModal[item.valueKey] = e
            },
            'onUpdate:val': e => {
              formModal[item.valueKey] = e
              item.changeData?.(e, formModal)
            },
            'onUpdate:data': e => {
              /**处理自定义获取数据 */
              formModal.customData = e
            },
          })

        break
      default:
        method = () => <span style="color:red">render [{type}] Module does not exist</span>
    }
    return method
  }
  /**
   * 渲染配置项
   */

  const renderPropsItem = (props: DiyConfigOptions, formModal) => {
    let method = renderMethod(props, formModal)
    /**
     * 过滤掉字段中的所有空格
     * json字符串定位问题麻烦 这里统一处理
     */
    Object.keys(props).forEach(key => {
      if (typeof props[key] == 'string') props[key] = props[key].trim()
    })
    if (props.hidden?.(formModal)) return <span></span>
    if (props.type == 'drag-list') {
      return method(props, formModal)
    } else
      return (
        <FormItem label={props.label} field={props.valueKey} rules={[{ required: props?.formItemProps?.required ?? true, message: '请输入' + props.label }]} validate-trigger={['change', 'blur']} {...props.formItemProps}>
          <div class="flex-js" style="flex:2">
            {method(props, formModal)}
          </div>
        </FormItem>
      )
  }
  /**渲染拖转的列表 */
  const renderDragList = (props: DiyConfigDragOptions, formModal) => {
    const [imgProps] = (props.dragOption as DiyConfigDefaultOption[])!.filter(f => f.type == 'upload')
    const contentProps = (props.dragOption as DiyConfigDefaultOption[])!.filter(f => f.type != 'upload')
    const _renderForm = (props: DiyConfigOptions, index) => {
      const modal = formModal?.dragList?.[index]
      let method = renderMethod(props, modal)
      return props.hidden?.(modal) ? (
        <></>
      ) : (
        <FormItem label={props.label} label-col-props={{ span: 5 }} wrapper-col-props={{ span: 18 }} field={props.valueKey} {...props.formItemProps}>
          {method(props, modal)}
        </FormItem>
      )
    }
    const onClick = () => {
      const _pushItem = {}
      Object.keys(formModal.dragList[0]).forEach(key => {
        _pushItem[key] = ''
      })
      formModal.dragList.push(_pushItem)
    }
    const handleRemove = index => {
      if (formModal.dragList.length == 1) {
        message({ content: '最少保留1个', type: 'warning' })
        return
      }
      formModal.dragList.splice(index, 1)
    }
    return (
      <div class="list mb10">
        <Draggable
          list={formModal.dragList}
          handle=".move-icon"
          style="margin-bottom:20px"
          itemKey="valKey"
          v-slots={{
            item: ({ element, index }) => {
              return (
                <div class="item drag-item">
                  <div class="flex-center">
                    <div class="move-icon flex" style="cursor:move">
                      <icon-drag-dot-vertical size="30" style="color:#e5e5e5;margin:auto" />
                    </div>
                    <div class="upload mr20">{imgProps ? renderUpload(imgProps, element) : ''}</div>
                    <div class="content" style="flex:2">
                      <Space direction="vertical" style="width:100%">
                        {contentProps.map(item => {
                          return _renderForm(item, index)
                        })}
                      </Space>
                    </div>
                    {props.hideBtn ? (
                      <></>
                    ) : (
                      <Button
                        type="primary"
                        status="danger"
                        onClick={() => handleRemove(index)}
                        v-slots={{
                          icon: () => <icon-close />,
                        }}
                      />
                    )}
                  </div>
                </div>
              )
            },
          }}
        ></Draggable>
        {props.hideBtn ? (
          <></>
        ) : (
          <Button type="primary" long onClick={() => onClick()}>
            添加模块
          </Button>
        )}
      </div>
    )
  }

  /**渲染基础组件start------------ */
  const renderTextarea = (props: DiyConfigDefaultOption, formModal) => {
    return <a-textarea placeholder="请输入" v-model={formModal[props.valueKey]} />
  }
  const renderUpload = (props: DiyConfigDefaultOption, formModal) => {
    return <Upload {...props} list={formModal[props.valueKey]} v-model:value={formModal[props.valueKey]} />
  }
  const renderSelect = (props: DiyConfigDefaultOption, formModal) => <Select placeholder="请选择" onChange={e => props.onChange?.(e, formModal)} {...componentOptions(props, formModal)} allow-search options={props.options} v-model={formModal[props.valueKey]} />

  const renderInput = (props: DiyConfigDefaultOption, formModal) => <Input v-model={formModal[props.valueKey]} {...componentOptions(props, formModal)} placeholder={'请输入' + props.label} />

  const renderInputNumber = (props: DiyConfigDefaultOption, formModal) => {
    return (
      <div class="flex-center flex-js" style="flex:2">
        {/* <a-slider v-model={formModal[props.valueKey]} {...componentOptions(props,formModal)} style="width:150px;" /> */}
        {/* <p style="width:30px"></p> */}
        <InputNumber v-model={formModal[props.valueKey]} {...componentOptions(props, formModal)} hide-button placeholder={'请输入' + props.label} />
      </div>
    )
  }

  const renderColor = (props: DiyConfigDefaultOption, formModal) => (
    <div>
      {props.type == 'color' ? (
        <ColorPicker v-model={formModal[props.valueKey]} showText {...componentOptions(props, formModal)} style="margin-left:auto" />
      ) : (
        <Space>
          <ColorPicker v-model={formModal[props.valueKey][0]} showText {...componentOptions(props, formModal)} style="margin-left:auto" />
          <ColorPicker v-model={formModal[props.valueKey][1]} showText {...componentOptions(props, formModal)} style="margin-left:auto" />
        </Space>
      )}
    </div>
  )

  const renderSwitch = (props: DiyConfigDefaultOption, formModal) => <Switch v-model={formModal[props.valueKey]} {...componentOptions(props, formModal)} />

  const renderRadio = (props: DiyConfigDefaultOption, formModal) => <RadioGroup options={props.options} v-model={formModal[props.valueKey]} {...componentOptions(props, formModal)} />
  const renderCheckboxGroup = (props: DiyConfigDefaultOption, formModal) => <a-checkboxGroup options={props.options} v-model={formModal[props.valueKey]} {...componentOptions(props, formModal)} />

  const renderRadioBtn = (props: DiyConfigDefaultOption, formModal) => {
    const name = computed(() => (props.options as RadioButtonOption[])?.filter(f => f.value == formModal[props.valueKey])?.[0]?.name)
    return (
      <div class="flex-js flex-center" style="flex:2">
        <span>{name.value}</span>
        <RadioGroup options={props.options} type="button" v-model={formModal[props.valueKey]} {...componentOptions(props, formModal)} />
      </div>
    )
  }
  /**基础组件end------------------ */
  return { renderPropsItem, renderMethod }
}
